package eva

import (
	"context"
	"trusteva/app/eva/model"

	"trusteva/app/eva/internal/svc"
	"trusteva/app/eva/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListRuleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListRuleLogic {
	return &ListRuleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListRuleLogic) ListRule(req *types.ListRuleRo) (resp *types.ListRuleRsp, err error) {
	sess := l.svcCtx.DB.WithContext(l.ctx).Model(&model.Rule{})
	if req.AppId != "" {
		sess = sess.Where("AppId=?", req.AppId)
	}
	if req.DeviceId != "" {
		sess = sess.Where("DeviceId=?", req.DeviceId)
	}
	if req.DstIP != "" {
		sess = sess.Where("DstIP=?", req.DstIP)
	}
	if req.DstPort != "" {
		sess = sess.Where("DstPort=?", req.DstPort)
	}
	if req.Status != "" {
		sess = sess.Where("Status=?", req.Status)
	}
	if req.UserId != "" {
		sess = sess.Where("UserId=?", req.UserId)
	}

	var total int64
	if err := sess.Count(&total).Error; err != nil {
		return nil, err
	}
	var beans []model.Rule
	if err := sess.Order("ID DESC").Limit(req.Size).Offset((req.Page - 1) * req.Size).
		Find(&beans).Error; err != nil {
		return nil, err
	}

	resp = new(types.ListRuleRsp)
	resp.Total = total
	for _, v := range beans {
		var ac = types.ListRuleData{
			Id:       v.ID,
			AppId:    v.AppId,
			DeviceId: v.DeviceId,
			DstIP:    v.DstIP,
			DstPort:  v.DstPort,
			Status:   v.Status,
		}
		resp.Items = append(resp.Items, ac)
	}
	return
}
